import {goodsList,goodsCount} from '../../../request/api'

const state = {
    goodslist:[],
    size:5,//页面显示的条数
    page:1, //页码初始值
    count:5 //总数
}

const getters = {
    // 返回管理员列表
    getGoodsList(state){
        return state.goodslist
    },
    //返回总数
    getCount(state){
        return state.count
    },
    //返回当前显示条数
    getSize(state){
        return state.size
    }
}

const mutations = {
    REQ_GOODSLIST(state,payload){
        // console.log(payload);
        state.goodslist = payload
    },
    REQ_GETCOUNT(state,payload){
        state.count = payload
    },
    //修改页码
    CHANGE_PAGE(state,payload){
        state.page = payload
    }
}
const actions = {
    // 封装一个获取规格列表的行动
    getGoodsListActions(context){
        goodsList({
            size:context.state.size,
            page:context.state.page
        }).then(res => {
            // console.log(res);
            if(res.code == 200){
                context.commit('REQ_GOODSLIST',res.list)
                let list = res.list ? res.list :[]
                if(context.state.page !=1 && list.length==0 ){
                    context.dispatch('changePageActions',context.state.page-1)
                }
            }
        })
    },
    // 封装一个获取总数的行动
    getCountActions({commit}){
        goodsCount()
        .then(res =>{
            // console.log(res);
            if(res.code==200){
                commit('REQ_GETCOUNT',res.list[0].total)
            }
        })
    },
    // 疯转一个切换页码事件
    changePageActions(context,payload){
        //第一、当用户切换页码，我们要修改page
        context.commit('CHANGE_PAGE',payload)
        // console.log(payload);
        //第二、重新调用列表
         context.dispatch('getGoodsListActions')
    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    // 开启命名空间
    namespaced:true
}